package com.gateway.config.annotation.log;

import com.alibaba.fastjson.JSONObject;
import com.gateway.common.holder.RequestHolder;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.util.StopWatch;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;

/**
 * @author admin
 */
@Aspect
@Component
@Order(Ordered.HIGHEST_PRECEDENCE)
@Slf4j
public class UserOperationLogAspect {
    private static final String UNIQUE_ID = "TRACE_ID";

    @Pointcut("@annotation(com.gateway.config.annotation.log.UserOperationLog)")
    public void operationLogCut() {

    }
    @Around("operationLogCut()")
    public Object userOperationLog(ProceedingJoinPoint point) throws Throwable {
        //获取秒表计算耗时
        StopWatch stopWatch = new StopWatch();
        stopWatch.start();
        UserLog userLog = new UserLog();
        //获取用户
        HttpServletRequest httpServletRequest = RequestHolder.getRequest();

        //获取请求类型
        userLog.setRequestType(httpServletRequest.getMethod());

        // 获取注解
        MethodSignature signature = (MethodSignature) point.getSignature();
        Method method = signature.getMethod();

        //反射获取方法名称
        String methodName = method.getName();
        UserOperationLog userOperationLog = method.getAnnotation(UserOperationLog.class);
        //执行的方法
        userLog.setExecuteMethod(methodName);

        //获取用户操作内容
        String operationContent = userOperationLog.value();
        userLog.setOperationName(operationContent);

        //接口名称
        userLog.setInterfaceName(userOperationLog.interfaceName());

        Object proceed = point.proceed();
        return proceed;
    }
}
